
<template>
	<view>
		<view class="confirm-order">
			<view class="confirm-con">
                <!-- 地址 -->
				<navigator hover-class="none" url="/pages/user_address/user_address?type=1">
					<address-item :address="address" />
				</navigator>
                
                <!-- 商品信息 -->
				<view class="goods contain">
                    <view class="lease-goods">
                        <lease-order-goods :image="goods.image">
                            <template #name>{{ goods.goods_name }}</template>
                            <template #specs>
                                {{ goods.spec_value_str }}，
                                {{ goods.periods }}{{ getPeriodsUnit(goods.periods_attribute) }}
                            </template>
                            <template #price>
                                <price 
								  :content="oneDayPrice" 
								  mainSize="38rpx" 
								  minorSize="24rpx" 
								  color="#333333" 
								  :isPrefix="true" 
								  :isSuffix="true" 
								/>
                                <text>（x{{ goods.periods }}期）</text>
                            </template>
                        </lease-order-goods>
                    </view>

					<view class="item row-between">
						<view>配送方式</view>
						<view>快递</view>
					</view>
					<view class="item row-between">
						<view>买家留言</view>
						<u-input 
                          v-model="userRemark" 
                          class="flex1 ml20" 
                          :clearable="false" 
                          placeholder="请添加备注（150字以内）" 
                        />
					</view>
				</view>
                
                <!-- 分期费用明细 -->
				<view class="periods-price contain">
					<view class="periods-price-item">
						<view class="lighter periods-price-row row-between">
							<view>总租金</view>
							<view>¥{{ goods.total_rent }}</view>
						</view>
						<view class="lighter periods-price-row row-between">
							<view>租期</view>
							<view>{{ goods.periods }}期</view>
						</view>
						<view class="lighter periods-price-row row-between">
							<view>每期应还</view>
							<view>¥{{ goods.issue_rent }}</view>
						</view>
					</view>
				</view>
                <view class="periods-price contain">
                    <view class="periods-price-item">
                        <view>
                            <view class="lighter periods-price-row row-between">
                                <view>首期租赁金额</view>
                                <view>¥{{ goods.issue_rent }}</view>
                            </view>
							<template v-if="orderInfo.insurance !== null">
								<view class="lighter periods-price-row row-between">
								    <view>保险套餐</view>
								    <view>+¥{{ orderInfo.insurance || '0.00' }}</view>
								</view>
							</template>
							<view class="lighter periods-price-row row-between">
							    <view>保证金</view>
							    <view>+¥{{ goods.deposit }}</view>
							</view>
                        </view>
						
						<view class="row-between periods-price-title">
						    <view class="ornament">应付金额</view>
						    <view class="ornament">¥{{ goods.first_pay_amount }}</view>
						</view>
                    </view>
                </view>
                
                
                <!-- 费用明细 -->
				<view class="price contain">
					<view class="item row-between">
						<view>运费</view>
						<view>¥{{orderInfo.shipping_price || '0.00'}}</view>
					</view>
				</view>
                
                
                <!-- 支付方式 -->
                <view class="pay-way contain">
                	<view class="lighter title">支付方式</view>
                	<radio-group class="radio-group" @change="radioChange">
                		<label v-for="(item, index) in payWayArr" :key="index" class="item row-between">
                			<view class="row">
                				<image class="icon-lg mr20" :src="item.icon" />
                				<view class>
                					<view class="balck bt10">{{item.name}}</view>
                					<view class="muted xs">{{item.extra}}</view>
                				</view>
                			</view>
                			<radio class="radio" :value="String(item.pay_way)" :checked="item.pay_way == payWay" />
                		</label>
                	</radio-group>
                </view>

			</view>
            
            <!-- 订单结算 -->
			<view class="footer bg-white fixed">
				<u-checkbox-group>
					<u-checkbox v-model="isAgreeProtocol" shape="circle">
				        <view class="sm row">
				            <view class="lighter">已阅读并同意协议</view>
				            <view class="primary" @tap.stop="showLeaseProtocol = true">《租赁协议》</view>
				        </view>
				    </u-checkbox>
				</u-checkbox-group>
				<view class="row-between">
					<view class="all-price lg row">
						<text>合计：</text>
						<view class="ornament">
					        <price 
					          :content="(goods.first_pay_amount)" 
					          mainSize="38rpx" 
					          minorSize="30rpx" 
					          :isSuffix="false" 
					          :isPrefix="true"
					        />
						</view>
					</view>
					<button 
					  class="btn br60 white" 
					  size="md" 
					  hover-class="none" 
					  @tap="onSubmitOrder"
					>
						提交订单
					</button>
				</view>
			</view>
		</view>
        
		<loading-view v-if="showLoading" background-color="transparent" :size="50" />
		<loading-view v-if="isFirstLoading" />
		
		
		<!-- 租赁用户协议 -->
		<u-popup v-model="showLeaseProtocol" mode="center" border-radius="20">
			<view class="protocol">
				<view class="protocol-title">租赁用户协议</view>
				<scroll-view scroll-y="true" class="protocol-content">
					<u-parse :html="protocolHtml" />
				</scroll-view> 
				<view class="protocol-confirm" @tap="showLeaseProtocol = false">我知道了</view>
			</view>
		</u-popup>
		
		<!-- 支付密码 -->
		<set-pay-pwd ref="setPayPwd" @confirm="orderBuyFun" />
	</view>
</template>

<script>
    import {
    	prepay,
    	getMnpNotice,
		getAlipayPayStatus
    } from '@/api/app';
    
    import {
    	wxpay,
    	alipay
    } from '@/utils/pay'
    
    import { 
        payment,
        leaseBuy,
		getLeaseProtocol
    } from '@/api/lease.js'
    
	import { getOrderCoupon } from '@/api/order';
    
	export default {
		data() {
			return {
				isFirstLoading: false && true,
				showLoading: false,
				address: {},            	// 当前地址信息
				orderInfo: {},          	// 订单信息
				goods: {},              	// 商品数据
				addressId: '',          	// 所选地址ID
				userRemark: '',         	// 留言
                
				popActive: 0,           	// 优惠券Tabs当前索引
                
				payWayArr: [],          	// 支付方式列表
				payWay: '',             	// 所选的支付方式
				
				payload: null,				// 已选规格
				isAgreeProtocol: false,		// 协议是否同意
				showLeaseProtocol: false,	// 协议 Popup
				protocolHtml: '',			// 富文本协议内容
			};
		}, 
		
		computed: {
			// 每天多少钱
			oneDayPrice() {
				const unit = this.goods.periods_attribute;
				const issueRent = this.goods.issue_rent;
				switch(unit) {
					case 'is_week': 
						return Number((issueRent / 7).toString().match(/^\d+(?:\.\d{0,2})?/));
					case 'is_month': 
						return Number((issueRent / 30).toString().match(/^\d+(?:\.\d{0,2})?/));
				}
			},	
		},
        
		methods: {
            // 输出分期单位
            getPeriodsUnit(value) {
                switch(value) {
                    case 'is_week': return '周';
                    case 'is_month': return '个月';
                }
            },
            
            // 选择支付方式
			radioChange(e) {
                const value = e.detail.value;
				this.payWay =  value * 1;
			},
        
            // 微信
            getAuthMsg() {
            	return new Promise(resolve => {
            		getMnpNotice({
            			scene: 1
            		}).then(res => {
            			if (res.code == 1) {
                            const data = res.data;
            				uni.requestSubscribeMessage({ tmplIds: data });
            			}
            			resolve();
            		});
            	});
            },
            
            // 点击下单
            onSubmitOrder() {
				if (!this.isAgreeProtocol) 
				  return uni.showToast({ title: '请先阅读并同意协议', icon: 'none' });
				if (!this.addressId)
				  return uni.showToast({ title: '请选择收货地址', icon: 'none' });
				
            	uni.showModal({
            		title: '温馨提示',
            		content: '是否确认下单?',
            		confirmColor: '#FF2C3C',
            		success: async res => {
            			if (!res.confirm) return;
						
            			// #ifdef MP-WEIXIN
            			await this.getAuthMsg();
            			// #endif
						
						if (this.payWay == 3) {
							this.$refs.setPayPwd.hasPayWord().then(res => {
								this.$refs.setPayPwd.showInputPwd();
							});
						} else {
							this.orderBuyFun();
						}
            		}
            	});
            },

            // 下单处理
			orderBuyFun(password) {
				this.showLoading = true;
                if(!this.payWayArr.length) {
                    this.showLoading = false;
                    return this.$toast({ title: '请联系管理员配置支付方式' });
                }
                
                const address = this.address;
                const goods = this.goods;
                
				const submitObj = {
					action: 'submit',
                    type: 'buy_now',
					goods: [{
                        lease_goods_id: goods.id,
                        item_id: goods.item_id,
                        goods_num: goods.goods_num,
                        periods_id: goods.periods_id,
                        remark: this.userRemark
                    }],
					insurance: goods.insurance,
					pay_way: this.payWay,
					address_id: this.addressId,
					pay_password: password
				};
                
                leaseBuy(submitObj).then(res => {
                   const data = res.data;
				   const code = res.code;
                   const order_id = data.order_id;
                   const type = data.from;
                   this.showLoading = false;
				   
				   prepay({
				   	from: type,
				   	order_id: order_id
				   }).then(({ code, data }) => {
						switch(code) {
						   // 微信支付
						    case 1: 
								this.payWeChat(data, order_id);
								break;
							// 支付宝支付
							case 20001:
								this.payAliPay(data, order_id);
								break;
							// 余额支付
							case 10001:
									uni.redirectTo({ 
										url: '/bundle/pages/lease_pay_result/lease_pay_result'
										  + '?id=' + order_id 
									});
								break;
						}
				   }).catch(err => {
						this.$toast({ title: '支付失败，请重试' });
						console.log(err);
				   });
                });
			},
			
			// 微信支付
			payWeChat(data, orderID) {
				wxpay(data).then(res => {
					if(res == 'success') {
						uni.redirectTo({
							url: '/bundle/pages/lease_pay_result/lease_pay_result'
							  + '?id=' + orderID 
						});
					}else {
						uni.redirectTo({
							url: '/bundle/pages/lease_order_detail/lease_order_detail'
							  + '?id=' + orderID 
						});
					}
				})
			},
			
			// 支付宝支付
			payAliPay(data, orderID) {
				
				// #ifdef H5
				alipay(data);
				// #endif
				
				// #ifdef MP-ALIPAY
				const tradeNo = data?.data?.trade_no;
				my.tradePay({
				  // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
				  tradeNO: tradeNo,
				  success: (res) => {
					  getAlipayPayStatus({ trade_no: tradeNo }).then(res => {
					  	if (res.tradeStatus == 'TRADE_SUCCESS') {
					  		uni.redirectTo({
					  			url: '/bundle/pages/lease_pay_result/lease_pay_result'
					  			  + '?id=' + orderID 
					  		});
					  	} else {
					  		uni.redirectTo({
					  			url: '/bundle/pages/lease_order_detail/lease_order_detail'
					  			  + '?id=' + orderID 
					  		});
					  	}
					  });
				  },
				  fail: (res) => {
						uni.redirectTo({
							url: '/bundle/pages/lease_order_detail/lease_order_detail'
							  + '?id=' + orderID 
						});
				  }
				});
				// #endif
			}
		},
		
		
		onLoad(options) {
		    const data = JSON.parse(decodeURIComponent(options.data));
			this.payload = data;
		    
		    // 选择地址
			uni.$on("selectaddress", e => {
		        const id = e.id;
		        const address = e.address;
		        
		        this.addressId = e.id
		        this.address = address;
		    });
		    
		    // 获取付款方式
		    payment().then(res => {
		        if (res.code != 1) return;
		        const data = res.data;
		        this.payWayArr = data;
		        this.payWay = data.length ? data[0].pay_way : 0
		    });
			
			// 获取协议内容
			getLeaseProtocol().then(res => {
				console.log(res);
				if (res.code != 1) return;
				this.protocolHtml = res.data || '';
			});
		},
		
		onShow() {
			const data = this.payload;

			leaseBuy({
				...data,
				address_id: this.addressId,
				action: 'info',
				type: 'buy_now'
			}).then(res => {
				if (res.code != 1) return;
				const data = res.data;
				this.orderInfo = data;
				this.address = data.address;
				this.addressId = data?.address?.id || '';
				this.goods = data.goods_lists[0];

			});
		},
		
		onUnload() {
			uni.$off("selectaddress");
		},

	}
</script>
<style>
	.confirm-order .confirm-con {
		overflow: hidden;
		padding-bottom: calc(126rpx + 20rpx + env(safe-area-inset-bottom));
	}

	.confirm-order .contain {
		border-radius: 14rpx;
		margin: 20rpx 20rpx 0;
		background-color: #fff;
		overflow: hidden;
	}

	.confirm-order .img-line {
		height: 1.5px;
		width: 100%;
		display: block;
	}


	.confirm-order .coupons {
		height: 100rpx;
		padding: 0 24rpx;
	}

	.goods .title {
		padding: 22rpx 24rpx;
		border-bottom: 1px solid #F6F6F6;
	}

	.goods .all-num {
		padding: 22rpx 24rpx;
		border-bottom: 1px dotted #F6F6F6;
	}
    
    .lease-goods {
        padding: 24rpx 20rpx;
    }

	.confirm-order .footer {
		box-sizing: content-box;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 126rpx;
		padding-left: 20rpx;
		padding-right: 20rpx;
		padding-top: 10rpx;
		padding-bottom: env(safe-area-inset-bottom);
	}


	.confirm-order .pay-way .title {
		padding: 20rpx 24rpx;
	}

	.confirm-order .pay-way .radio-group .item {
		height: 120rpx;
		padding: 0 24rpx;
	}

	.confirm-order .price {
		padding: 28rpx 20rpx;
	}

	.confirm-order .price .item:not(:last-of-type) {
		margin-bottom: 20rpx;
	}

	.confirm-order .goods>.item,
	.confirm-order .benefit>.item {
		padding: 0 24rpx;
		height: 80rpx;
	}

	.confirm-order .btn {
		background-color: #24A3FF;
		padding: 0 50rpx;
	}

	.confirm-order .van-cell:after {
		border: none;
	}

	.goods .shop-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.pop-title {
		height: 100rpx;
		border-bottom: 1rpx solid #F2F2F2;
	}

	.pop-title .title {
		margin-left: 30rpx;
		font-size: 34rpx;
		font-weight: bold;
		line-height: 36rpx;
	}
    
    .periods-price {
        padding: 0 20rpx;
    }
    
    .periods-price-item {
        padding: 20rpx 0;
    }
    
    .periods-price-item:nth-child(n + 2) {
        border-top: 1px solid #E5E5E5;
    }
    
    .periods-price-title {
        padding: 10rpx 0;
        font-size: 30rpx;
        font-weight: 500;
        color: #333333;
    }
    
    .periods-price-row {
        padding: 10rpx 0;
        font-size: 26rpx;
    }
	
	
	.protocol {
		display: flex;
		flex-direction: column;
		width: 88vw;
		height: 88vh;
		padding: 20rpx;
		background-color: #FFFFFF;
	}
	
	.protocol-title {
		padding: 20rpx 0;
		font-size: 32rpx;
		font-weight: 500;
		text-align: center;
		color: #333333;
	}
	
	.protocol-content {
		flex: 1;
		overflow: scroll;
	}
	
	.protocol-confirm {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 72rpx;
		border-radius: 50px;
		margin-top: 20rpx;
		font-size: 32rpx;
		background-color: #24A3FF;
		color: #FFFFFF;
	}
</style>
